<template>
  <topNav
    title="扫描模式"
    @save="saveFun"
    rType="code"
    @orcode="orFun"
  ></topNav>
  <view class="camera_page">
    <view class="camera_content">
      <view class="code_close" @click="closeClick()">
        <!-- <img src="../../static/close.png"> -->
      </view>
      <view class="loop_line"></view>
      <view class="video_nav">
        <video id="video_nav_id" autoplay :controls="false"></video>
      </view>
    </view>
  </view>
</template>
<script setup>
import topNav from "../components/topNav.vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { reactive, onMounted, onUnmounted, ref, nextTick } from "vue";
import { BrowserMultiFormatReader } from "@zxing/library"; //npm引入
// import { BrowserMultiFormatReader } from '@/utils/zxing.js' //直接引入js文件
import { useCodeStore } from "@/stores/code.js";
import { appPayCreate } from "@/services/cashier";
const codeStore = useCodeStore();
let html5QrCode = ref(null);
const isShow = ref(true);
const devicesInfo = ref(false);
const orderid = ref("");
const payNum = ref(0);
const payPrice = ref(0);
const codeReader = ref(null);
const deviceId = ref(null);
const videoInputDevices = ref([]);
const type = ref("");
const typeindex = ref(false);
const initEvent = () => {
  // 这里的处理是因为uniapp会对video标签进行二次封装，如果是Vue的话直接获取video标签
  var video = document
    .getElementById("video_nav_id")
    .getElementsByTagName("video")[0]; // uniapp
  // var video = document.getElementById('video_nav_id') //Vue
  video.setAttribute("id", "video_id");
  video.setAttribute("class", "video_calss");
  codeReader.value = new BrowserMultiFormatReader();
  codeReader.value
    .listVideoInputDevices()
    .then((res) => {
      if (res.length > 0) {
        videoInputDevices.value = res;
        // 这里默认选择最后一个摄像头
        deviceId.value = res[res.length - 1].deviceId;
      } else {
        // 没有可用的摄像头
        // todo
        uni.showToast({ title: `无法获取设备信息`, icon: "none" });
      }
    })
    .catch((err) => {
      console.error(err);
    });
  startScanning();
};
onLoad((e) => {
  type.value = e.type;
  orderid.value = e.orderid ? e.orderid : "";
  payNum.value = e.payNum ? e.payNum : 0;
  payPrice.value = e.payPrice ? e.payPrice : 0;
  nextTick(() => {
    setTimeout(() => {
      initEvent();
    }, 500);
  });
  // setTimeout(() => {
  //   initEvent();
  // }, 3000);
});
const codeTrue = ref(false);
const isPayTo = ref(false);

onShow(() => {
  codeTrue.value = false;
  isPayTo.value = false;
});
const orFun = () => {
  typeindex.value = !typeindex.value;
  if (typeindex.value) {
    nextTick(() => {
      setTimeout(() => {
        initEvent2();
      }, 500);
    });
  } else {
    nextTick(() => {
      setTimeout(() => {
        initEvent();
      }, 500);
    });
  }
};
const initEvent2 = () => {
  // 这里的处理是因为uniapp会对video标签进行二次封装，如果是Vue的话直接获取video标签
  var video = document
    .getElementById("video_nav_id")
    .getElementsByTagName("video")[0]; // uniapp
  // var video = document.getElementById('video_nav_id') //Vue
  video.setAttribute("id", "video_id");
  video.setAttribute("class", "video_calss");
  codeReader.value = new BrowserMultiFormatReader();
  codeReader.value
    .listVideoInputDevices()
    .then((res) => {
      if (res.length > 0) {
        videoInputDevices.value = res;
        // 这里默认选择最后一个摄像头
        deviceId.value = res[0].deviceId;
      } else {
        // 没有可用的摄像头
        // todo
        uni.showToast({ title: `无法获取设备信息`, icon: "none" });
      }
    })
    .catch((err) => {
      console.error(err);
    });
  startScanning();
};
const startScanning = () => {
  try {
    codeReader.value.decodeFromVideoDevice(
      deviceId.value,
      "video_id",
      (res, err) => {
        if (res) handleScanningResult(res);
      }
    );
  } catch (err) {
    uni.showToast({ title: `初始化失败${err}`, icon: "none" });
  }
};
const handleScanningResult = async (res) => {
  // 这里处理扫描结果
  console.log(res.text);
  let decodedText = res.text;
  uni.showToast({ title: `扫描结果${res.text}`, icon: "none" });
  if (codeTrue.value) {
    return;
  }
  if (type.value == "payPrice") {
    if (isPayTo.value) {
      return;
    }
    isPayTo.value = true;

    try {
      let res = await appPayCreate({
        id: orderid.value,
        attach: "scan_pay",
        authCode: decodedText,
      });
      if (res.code == 200) {
        uni.redirectTo({
          url:
            "/pages/cashier/paystate/index?orderid=" +
            res.data.id +
            "&payNum=" +
            payNum.value,
        });
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
        uni.redirectTo({
          url:
            "/pages/cashier/paystate/index?orderid=" +
            res.data.id +
            "&payNum=" +
            payNum.value,
        });
      }
    } catch (e) {
      uni.showToast({
        title: e.msg,
        icon: "none",
      });
      uni.navigateBack();
    }

    return;
  }

  if (type.value == "addBarCode") {
    uni.setStorageSync("barCode", decodedText);
    // #ifdef H5
    history.back();

    // #endif
    // #ifndef H5
    uni.navigateBack();
    // #endif
  }
  if (type.value == "transfer") {
    showToast("扫码成功" + decodedText);
    setTimeout(() => {
      uni.redirectTo({
        url: "/pages/transfer/goods_search/index?code=" + decodedText,
      });
    }, 1000);
    return;
  }

  if (type.value == "price") {
    showToast("扫码成功" + decodedText);
    setTimeout(() => {
      uni.redirectTo({
        url: "/pages/goods/goods_price_search/index?code=" + decodedText,
      });
    }, 1000);
    return;
  }
  if (type.value == "goods") {
    showToast("扫码成功" + decodedText);
    setTimeout(() => {
      uni.redirectTo({
        url: "/pages/goods/goods_search/index?code=" + decodedText,
      });
    }, 1000);
    return;
  }
  devicesInfo.value = true;
  codeStore.setcode(decodedText);

  codeTrue.value = true;
  setTimeout(() => {
    uni.navigateBack();
  }, 1000);
};
// 停止扫描
const stopScanning = () => {
  codeReader.value.reset();
};

const closeClick = () => {
  // todo
};

onUnmounted(() => {
  stopScanning();
});
</script>
<style scoped lang="scss">
.camera_page {
  height: calc(100vh - 88rpx);
  width: 100vw;
}

.camera_content {
  height: 100%;
  width: 100%;
  position: relative;
}

.code_close {
  height: 50rpx;
  width: 50rpx;
  position: absolute;
  left: 30rpx;
  top: 30rpx;
  z-index: 999999;
}

.code_close > img {
  height: 100%;
  width: 100%;
  display: block;
}

.loop_line {
  height: 3px;
  width: 80%;
  background-color: aliceblue;
  border-radius: 50%;
  box-shadow: 1px -4px 25px 7px rgba(255, 255, 255, 0.5);
  position: absolute;
  left: 50%;
  top: 20%;
  transform: translateX(-50%);
  animation: myfirst 3s infinite;
  z-index: 999999;
}

@keyframes myfirst {
  from {
    top: 20%;
  }

  to {
    top: 80%;
  }
}

.video_nav {
  height: 100%;
  width: 100%;
}

#video_nav_id {
  height: 100%;
  width: 100%;
}

:deep(.uni-video-cover) {
  display: none;
}
</style>
